package com.digitalchina.lxnsy.activity.old;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;

import com.apkfuns.logutils.LogUtils;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessFile;
import com.digitalchina.lxnsy.api.BusinessQandA;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.FileVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.view.richeditor.AnswerQuestionRichTextEditor;
import com.digitalchina.lxnsy.view.richeditor.AnswerQuestionRichTextEditor.EditData;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/2/9 11:17
 * 修改备注：
 * ================================================
 */
public class AnswerQuestionActivity extends BaseActivity {

    private static final int REQUEST_CODE_PICK_IMAGE = 1023;
    private static final int REQUEST_CODE_CAPTURE_CAMEIA = 1022;
    public static final int RESULT_ANSWER_QUESTION_CODE = 0x2; // result code

    private AnswerQuestionRichTextEditor editor;
    private View btn1, btn2, btn3;
    private View.OnClickListener btnListener;

    private static final File PHOTO_DIR = new File(
            Environment.getExternalStorageDirectory() + "/DCIM/Camera");
    private File mCurrentPhotoFile;// 照相机拍照得到的图片

    private String imagePath = ""; // 每次插入图片的绝对路径
    private String questionId = ""; // 问题ID  上个页面带过来

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_answer_question_html);
        setTitle("回答");
    }

    @Override
    public void initMember() {

        if (getIntent().hasExtra("questionId"))
            questionId = (String) getIntent().getSerializableExtra("questionId");

        editor = (AnswerQuestionRichTextEditor) findViewById(R.id.richEditor);
        btnListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                editor.hideKeyBoard();
                if (v.getId() == btn1.getId()) {
//                    // 打开系统相册
//                    Intent intent = new Intent(Intent.ACTION_PICK);
//                    intent.setType("image/*");// 相片类型
//                    startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
                    Intent intent = new Intent(AnswerQuestionActivity.this, ImageGridActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
                } else if (v.getId() == btn2.getId()) {
                    // 打开相机
//                    openCamera();
                } else if (v.getId() == btn3.getId()) {
                    List<EditData> editList = editor.buildEditData();
                    // 下面的代码可以上传、或者保存，请自行实现
                    sendEditData(editList);
                }
            }
        };

        btn1 = findViewById(R.id.button1);
        btn2 = findViewById(R.id.button2);
        btn3 = findViewById(R.id.button3);

        btn1.setOnClickListener(btnListener);
        btn2.setOnClickListener(btnListener);
        btn3.setOnClickListener(btnListener);

    }

    /**
     * 发送消息到服务器
     */
    protected void sendEditData(List<EditData> editList) {

        String sendMsg = "";
        String noFormaterContent = "";

        for (EditData itemData : editList) {
            if (itemData.inputStr != null) {
                LogUtils.e("commit inputStr=" + itemData.inputStr);
                sendMsg += "<p> " + itemData.inputStr + " </p>";
                noFormaterContent += itemData.inputStr;
            } else if (itemData.imagePath != null) {
                LogUtils.e("commit imagePath=" + itemData.imagePath);
                sendMsg += imgToHtml(itemData.imageName);
            }
        }

        BusinessQandA.answerQuestion(this, questionId, sendMsg, noFormaterContent, mHandler);
    }

    private String imgToHtml(String imageName) {
        // 示例<img src="/FileService/show/dec7d0f5-b501-46a9-ab1d-99ec486c4365_m" alt="" />

        return "<p> <img src=\"/FileService/show/" + imageName + "_m\" alt=\"\" /> </p>";
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == REQUEST_CODE_PICK_IMAGE) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                imagePath = images.get(0).path;
                BusinessFile.imageCompressAndUpload(AnswerQuestionActivity.this, imagePath, mHandler);
            }
        }

    }


    /**
     * 添加图片到富文本剪辑器
     *
     * @param imagePath
     */
    private void insertBitmap(String imagePath, String imageName) {
        editor.insertImage(imagePath, imageName);
    }

    /**
     * 根据Uri获取图片文件的绝对路径
     */
    public String getRealFilePath(final Uri uri) {
        if (null == uri) {
            return null;
        }

        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = getContentResolver().query(uri,
                    new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG.MSG_ANSWER_QUESTION_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_ANSWER_QUESTION_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_FILE_UPLOAD_SUCCESS:
                        showToast("上传图片成功");
                        FileVO fileVO = FastJsonUtil.getBean(msg.obj.toString(), "body", "fileStorage", FileVO.class);
                        if (fileVO != null) {
                            File file = new File(imagePath);
                            insertBitmap(getRealFilePath(getImageContentUri(AnswerQuestionActivity.this, file)), fileVO.getName());
                        }
                        break;
                    case MSG.MSG_FILE_UPLOAD_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        showToast("回答成功");
        setResult(RESULT_ANSWER_QUESTION_CODE);
        finish();
    }

    @Override
    public void rightOnClick() {

    }

    /**
     * Gets the content:// URI from the given corresponding path to a file
     *
     * @param context
     * @param imageFile
     * @return content Uri
     */
    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    /**
     * Gets the corresponding path to a file from the given content:// URI
     *
     * @param selectedVideoUri The content:// URI to find the file path from
     * @param contentResolver  The content resolver to use to perform the query.
     * @return the file path as a string
     */
    public static String getFilePathFromContentUri(Uri selectedVideoUri,
                                                   ContentResolver contentResolver) {

        String filePath;
        String[] filePathColumn = {MediaStore.MediaColumns.DATA};

        Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
//      也可用下面的方法拿到cursor
//      Cursor cursor = this.context.managedQuery(selectedVideoUri, filePathColumn, null, null, null);

        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        filePath = cursor.getString(columnIndex);
        cursor.close();
        return filePath;
    }
}
